<script setup lang="ts">
import { bindMobile, loginByQQ } from '@/services/user'
import { onMounted, ref } from 'vue'
import { mobileRules, codeRules } from '@/utils/rules'
import { useSendMobileCode } from '@/composable'
import type { User } from '@/types/user'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'
import { showSuccessToast } from 'vant'

// 1. 调用三方登录接口
const openId = ref('')
const isNeedBind = ref(false)
onMounted(() => {
  // 1.1 判断是否QQ扫码登录成功
  if (window.QC.Login.check()) {
    // 1.2 获取openId
    window.QC.Login.getMe((id: string) => {
      // 1.3 记录openId
      openId.value = id
      // 1.4 使用openId去进行三方登录
      loginByQQ(openId.value)
        .then((res) => {
          // console.log('登录成功', res.data)
          // 后续处理
          loginSuccess(res.data)
        })
        .catch(() => {
          console.log('登录失败')
          isNeedBind.value = true // 需要绑定手机号
        })
    })
  }
})

// 2. 绑定手机号
const mobile = ref('')
const code = ref('')
// 2.1 获取短信验证码
const { formRef, time, send } = useSendMobileCode(mobile, 'bindMobile')
const bind = async () => {
  // 2.2 绑定手机号
  const res = await bindMobile({
    mobile: mobile.value,
    code: code.value,
    openId: openId.value
  })
  // 2.3 登录成功后处理
  // console.log(res)
  loginSuccess(res.data)
}

// 3. 登录成功后处理
const store = useUserStore()
const router = useRouter()
const loginSuccess = (user: User) => {
  // 3.1 存储用户到仓库
  store.setUser(user)
  // 3.2 跳转到个人中心
  // 如果有登录成功后的回跳地址则跳回跳地址, 没有则去个人中心
  router.replace(store.returnUrl || '/user')
  showSuccessToast('登录成功')
}
</script>

<template>
  <div class="login-page" v-if="isNeedBind">
    <cp-nav-bar title="QQ-三方登录"></cp-nav-bar>
    <div class="login-head">
      <h3>手机绑定</h3>
    </div>
    <van-form autocomplete="off" ref="formRef" @submit="bind">
      <!-- 手机号输入框 -->
      <van-field
        name="mobile"
        type="tel"
        v-model="mobile"
        placeholder="请输入手机号"
        :rules="mobileRules"
      />
      <!-- 短信验证码输入框 -->
      <van-field
        type="text"
        v-model="code"
        :rules="codeRules"
        placeholder="请输入验证码"
      >
        <template #button>
          <span class="btn-send" :class="{ active: time > 0 }" @click="send">
            {{ time > 0 ? `${time}s后再次发送` : '发送验证码' }}</span
          >
        </template>
      </van-field>
      <div class="cp-cell">
        <van-button
          style="margin-top: 50px"
          block
          round
          type="primary"
          native-type="submit"
        >
          立即绑定
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<style lang="scss" scoped>
@import '@/styles/login.scss';
</style>
